
//
//  TalkingViewController.m
//  QuanZiChat
//
//  Created by lanou3g on 15/11/25.
//  Copyright © 2015年 ZhongHongLin. All rights reserved.
//

#import "TalkingViewController.h"
#import "MessageInfo.h"
#import "MessageFrame.h"
#import "ChatingTableViewCell.h"
#import "ContactManManager.h"
#import <AVOSCloudIM.h>
#import "TalkManage.h"
#import "Person.h"
#import "TalkRecord.h"


@interface TalkingViewController ()<UITableViewDelegate,UITableViewDataSource,AVIMClientDelegate>
@property (weak, nonatomic) IBOutlet UITextField *taxtFiled;
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (weak, nonatomic) IBOutlet UIButton *sendbutton;
@property(nonatomic,strong)NSMutableArray *MessageFrameArray;
@property(nonatomic,strong)NSString *time;
@property(nonatomic,strong)Person *person;
@property(nonatomic,strong)NSArray *ChattingRecordsArray;

@end

@implementation TalkingViewController

#pragma mark ================= viewDidLosd及其相关方法
- (void)viewDidLoad {
    [super viewDidLoad];
    [self basicAction];
    self.ChattingRecordsArray = [NSArray array];
    //输出存储路径
    [[TalkManage defulManage] applicationDocumentsDirectory];
    //获取自己的objectID
    AVUser *currentUser = [AVUser currentUser];
    self.MyClientID = currentUser.objectId;
    //监听键盘的弹出事件
    //1.创建NSNotification对象
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //2.监听键盘的弹出
    [center addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    //点击发送的button
    [self.sendbutton addTarget:self action:@selector(sendmessageWithtextFile:) forControlEvents:UIControlEventTouchUpInside];
    //接受信息的方法
    [[ContactManManager defaulManager] recriveMessageWithDelegate:self OtherClient:self.MyClientID];
    NSLog(@"%@",self.parentViewController);
    //点击返回Bar清空数组
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
    //判断是否要打开Person表
    if ([[TalkManage defulManage] fetchWithUserID:self.OtherClientID EntityForName:@"Person"].count > 0) {
        self.person = [[TalkManage defulManage] fetchWithUserID:self.OtherClientID EntityForName:@"Person"].lastObject;
    }else{
        self.person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:[TalkManage defulManage].managedObjectContext];
    }
    //调用将聊天记录按时间排序的方法(此方法包含从本地数据库查询聊天记录的方法)
    [[TalkManage defulManage] getMessageSortWithClick:self.OtherClientID];
}

#pragma mark ========= 基本方法
-(void)basicAction{
    //设置标题
    self.title = [NSString stringWithFormat:@"和%@的聊天",self.username];
    //注册cell
    [self.tableview registerClass:[ChatingTableViewCell class] forCellReuseIdentifier:@"cell"];
    //隐藏cell中间的分割线
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    //设置tableView的背景色
    self.tableview.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
    //取消选中
    self.tableview.allowsSelection = NO;
    //
    self.tabBarController.tabBar.hidden = YES;
}


#pragma mark ========== 其他方法实现
//button发送信息的方法
-(void)sendmessageWithtextFile:(UITextField *)textField{
    NSString *str = @"1";
    NSInteger num = [str integerValue];
    NSNumber *type = @(num);
    
    //1.调用发消息的方法
    [[ContactManManager defaulManager] sendMessageWithMyClientID:self.MyClientID OtherClientID:self.OtherClientID Message:self.taxtFiled.text];
    //调用coredata将信息保存到本地
    [self addContentWithEntityForType:type Time:@"10:00" Message:self.taxtFiled.text UserID:self.OtherClientID Username:self.username];
    //2.调用创建会话模型的方法
    [[ContactManManager defaulManager] buildSendModelWithString:self.taxtFiled.text type:@"1"];
    //3.tableview滚动到最后一行并刷新tableview
    //[self lastTableView];
    [self.tableview reloadData];
    //4.清空文本框并回收键盘
    self.taxtFiled.text = nil;
    [self.taxtFiled resignFirstResponder];
}


//tableView滚动到最后一行的方法
-(void)lastTableView{
    NSIndexPath *lastRowIndexPath;
    if ([[ContactManManager defaulManager] getTalkArray].count > 0 ) {
        lastRowIndexPath = [NSIndexPath indexPathForRow:[[ContactManManager defaulManager] getTalkArray].count - 1 inSection:0];
        [self.tableview scrollToRowAtIndexPath:lastRowIndexPath atScrollPosition:0 animated:YES];
    }
}

//监听键盘弹出的方法
-(void)keyboardWillChangeFrame:(NSNotification *)frame{
    CGRect rectEbd = [frame.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //弹出键盘的高度
    CGFloat keyboardY = rectEbd.origin.y;
    //平移的高度
    CGFloat tranformValue = keyboardY - self.view.frame.size.height;
    [UIView animateWithDuration:0.25 animations:^{
        //view的transform的平移量
        self.view.transform = CGAffineTransformMakeTranslation(0, tranformValue);
    }];
    //让tableView的最后一行滚动到最上面
    [self lastTableView];
}


//移除通知
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//收回键盘
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //那键盘收回(让控制器管理的View结束编辑状态)
    [self.view endEditing:YES];
}


-(void)leftAction:(UIBarButtonItem *)bar{
    [[[ContactManManager defaulManager] getTalkArray] removeAllObjects];
    [self.navigationController popViewControllerAnimated:YES];
}


//将聊天记录保存到本地
-(void)addContentWithEntityForType:(NSNumber *)type Time:(NSString *)time Message:(NSString *)message UserID:(NSString *)userID Username:(NSString *)username{
    //打开TalkRecord表
    TalkRecord *content = [NSEntityDescription insertNewObjectForEntityForName:@"TalkRecord" inManagedObjectContext:[TalkManage defulManage].managedObjectContext];
    //给TalkRecord表里属性赋值
    content.type = type;
    content.content = message;
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *timeString = [formatter stringFromDate:date];
    content.time = timeString;
    //给Person表里的属性赋值
    self.person.userID = userID;
    self.person.username = username;
    self.person.myname = self.MyClientID;
    [self.person addContentsObject:content];
    //调用保存数据方法
    [[TalkManage defulManage] saveContext];
}


#pragma mark ============== Delegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [[ContactManManager defaulManager] getTalkArray].count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    MessageFrame *messFrame = [[ContactManManager defaulManager] getTalkArray][indexPath.row];
    self.time = messFrame.messageinfo.time;
    cell.messFrame = messFrame;
    return cell;
}

//返回每个cell的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageFrame *messageframe = [[ContactManManager defaulManager] getTalkArray][indexPath.row];
    return messageframe.rowhight;
}

//接收消息的回调函数
- (void)conversation:(AVIMConversation *)conversation didReceiveTypedMessage:(AVIMTypedMessage *)message
{
    NSString *str = @"2";
    NSInteger num = [str integerValue];
    NSNumber *type = @(num);
    
    //调用coredata储存接受到得消息
    [self addContentWithEntityForType:type Time:self.time Message:message.text UserID:self.OtherClientID Username:self.username];
    
    [[ContactManManager defaulManager] buildSendModelWithString:message.text type:@"2"];
    [self.tableview reloadData];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}



@end
